package gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;

public class GetSizeDlg {
	private Shell _shell;
	private Text _widthText;
	private Text _heightText;
	private Runer _runer;
	private Point _originalSize;
	
	public interface Runer
	{
		public void OnClick(Point newSize);
	}
	
	public GetSizeDlg(Display display, Point currentSize, Point originalSize, Runer runer)
	{	
		_shell = new Shell(display);
		DlgUtils.Functions.SetCenter(display, _shell);
		_shell.setText("Please chose size.");
		_shell.setLayout(new GridLayout(3, false));
		
		_runer = runer;
		_originalSize = originalSize;
		
		_widthText = new Text(_shell, SWT.BORDER);
		_widthText.setText(String.valueOf(currentSize.x));
		_widthText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		_heightText = new Text(_shell, SWT.BORDER);
		_heightText.setText(String.valueOf(currentSize.y));
		_heightText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Button button = new Button(_shell, SWT.None);
		button.setText("Resize");
		button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		button.addMouseListener(
				new MouseListener()
				{
					public void mouseDoubleClick(MouseEvent e){}
					public void mouseDown(MouseEvent e){}
					public void mouseUp(MouseEvent e)
					{
						if (Validate())
						{
							_runer.OnClick(new Point(
									Integer.parseInt(_widthText.getText()), 
									Integer.parseInt(_heightText.getText())));

							_shell.dispose();
						}
					}
				});
		
		Link link = new Link(_shell, SWT.BORDER);
		link.setText(String.format("Original size (%d,%d)", _originalSize.x, _originalSize.y));
		link.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 3, 1));
		link.addMouseListener(
				new MouseListener()
				{
					public void mouseDoubleClick(MouseEvent e){}
					public void mouseDown(MouseEvent e){}
					public void mouseUp(MouseEvent e)
					{
						if (Validate())
						{
							_widthText.setText(String.valueOf(_originalSize.x));
							_heightText.setText(String.valueOf(_originalSize.y));
						}
				}});
		
		_shell.pack();
	}
	
	private boolean Validate()
	{
		try
		{
			Integer.parseInt(_widthText.getText());
			Integer.parseInt(_heightText.getText());
			return true;
		}
		catch(NumberFormatException e)
		{
			return false;
		}
	}
	
	public void Show()
	{
		_shell.open();
	}
	
	public Rectangle GetBounds()
	{
		return _shell.getBounds();
	}
}
